﻿using System.Reflection;

namespace NiuX.AspNetCore.MiniWebApi.Core.Middlewares;

/// <summary>
/// 嵌入资源中间件
/// </summary>
public class EmbeddedRresourceMiddleware
{
    private readonly RequestDelegate _next;

    private static readonly Dictionary<string, string> Maps = new()
    {
        { "github-markdown.css", AssetConsts.GithubMarkdownCss },
        { "github-markdown-dark.css", AssetConsts.GithubMarkdownDarkCss },
        { "github-markdown-light.css", AssetConsts.GithubMarkdownLightCss },
    };

    public EmbeddedRresourceMiddleware(RequestDelegate next)
    {
        this._next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        var path = context.Request.Path.Value ?? "";
        var first = Maps.FirstOrDefault(x => path.EndsWith(x.Key, StringComparison.OrdinalIgnoreCase));

        if (EqualityComparer<KeyValuePair<string, string>>.Default.Equals(first, default))
        {
            await _next(context);
            return;
        }

        var assembly = Assembly.Load("NiuX.AspNetCore");

        var stream = assembly.GetManifestResourceStream(first.Value);
        var buffer = new byte[stream!.Length];
        _ = await stream.ReadAsync(buffer, 0, buffer.Length);
        await context.Response.Body.WriteAsync(buffer);
    }
}